package com.ly.honor.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.ly.honor.util.MinioUtil;
import com.ly.honor.util.Result;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.http.Method;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author 李某人
 * @Date 2023/1/28 17:03
 * @Version 1.0
 */
@Controller
@RestController
@Api(tags = "Minio管理")
@RequestMapping("minio")
public class MinioController {

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioClient minioClient;

    @ApiOperation("创建桶")
    @PostMapping("/createBucket")
    public Result createBucket(String bucketName){
        minioUtil.createBucket(bucketName);
        return Result.ok("创建桶" + bucketName + "成功");
    }

    @ApiOperation("检查桶是否存在")
    @PostMapping("/bucketExists")
    public Result bucketExists(String bucketName){
        minioUtil.bucketExists(bucketName);
        return Result.ok("创建桶" + bucketName + "成功");
    }

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public Result upload(MultipartFile file,String fileName) throws Exception{
        String remoteName = "";
        if(fileName == null || "".equals(fileName)){
            remoteName = IdUtil.randomUUID();
        }else {
            remoteName = fileName;
        }
        minioUtil.uploadFile(file,"ly-bucket",minioUtil.getDatePath() + remoteName + ".jpg");
        String url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.GET).bucket("ly-bucket").object(minioUtil.getDatePath() + remoteName + ".jpg").build());
        System.out.println(url);
        return Result.ok("上传成功");
    }
}
